import logging
import os
from logging.handlers import TimedRotatingFileHandler
from ..config import BASE_DIR

# 创建日志目录
LOG_DIR = os.path.join(BASE_DIR, "logs")
if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)

def setup_logger(name='video_service'):
    """设置日志记录器"""
    logger = logging.getLogger(name)
    
    # 如果已经有处理器，不重复添加
    if logger.handlers:
        for handler in logger.handlers[:]:
            logger.removeHandler(handler)
    
    # 设置日志级别
    logger.setLevel(logging.INFO)
    
    # 禁用日志传播到父记录器
    logger.propagate = False
    
    try:
        # 使用模块名作为日志文件名
        log_file = os.path.join(LOG_DIR, f'{name}.log')
        
        # 创建按时间轮转的文件处理器
        file_handler = TimedRotatingFileHandler(
            filename=log_file,
            when='midnight',
            interval=1,
            backupCount=30,
            encoding='utf-8'
        )
        
        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        
        # 设置日志格式
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)
        
        # 添加处理器
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)
        
        # 测试日志记录
        logger.info(f"Logger '{name}' initialized successfully")
        
    except Exception as e:
        print(f"Error setting up logger: {str(e)}")
        raise
    
    return logger

# 创建默认日志记录器
try:
    logger = setup_logger()
except Exception as e:
    print(f"Failed to create default logger: {str(e)}")
    # 创建一个基本的控制台日志记录器作为后备
    logger = logging.getLogger('fallback')
    logger.setLevel(logging.INFO)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
    logger.addHandler(console_handler) 